#!/usr/bin/env Python3
# -*- encoding:utf-8 -*-
import uuid

import grpc
import osplugin.grpcpb.lcmservice_pb2 as lcmservice_pb2
import osplugin.grpcpb.lcmservice_pb2_grpc as lcmservice_pb2_grpc
from osplugin.tests.test_data import test_access_token, test_host_ip


def make_upload_request(access_token, host_ip, config_file_data):
    request0 = lcmservice_pb2.UploadCfgRequest(accessToken=access_token)
    request1 = lcmservice_pb2.UploadCfgRequest(hostIp=host_ip)
    request2 = lcmservice_pb2.UploadCfgRequest(configFile=config_file_data)
    requests = [request0, request1, request2]
    for request in requests:
        yield request


def make_instantiate_request(access_token, host_ip, app_instance_id, package_path):
    request0 = lcmservice_pb2.InstantiateRequest(accessToken=access_token)
    request1 = lcmservice_pb2.InstantiateRequest(hostIp=host_ip)
    request2 = lcmservice_pb2.InstantiateRequest(appInstanceId=app_instance_id)
    with open(package_path, 'rb') as package_file:
        package_data = package_file.read()
    request3 = lcmservice_pb2.InstantiateRequest(package=package_data)
    for request in [request0, request1, request2, request3]:
        yield request


def test_upload_config(client):
    response = client.uploadConfig(make_upload_request(test_access_token, test_host_ip, b'export OS_USER_NAME="mec"\n'))
    print(response.status)


def test_remove_config(client):
    response = client.removeConfig(lcmservice_pb2.RemoveCfgRequest(accessToken=test_access_token,
                                                                   hostIp=test_host_ip))
    print(response.status)


def test_instantiate(client):
    test_app_ins_id = ''.join(str(uuid.uuid4()).split('-'))
    print(test_app_ins_id)
    response = client.instantiate(make_instantiate_request(access_token=test_access_token,
                                                           host_ip=test_host_ip,
                                                           app_instance_id=test_app_ins_id,
                                                           package_path='./resources/test-csar.zip'))
    print(response.status)


def test_terminate(client):
    response = client.terminate(lcmservice_pb2.TerminateRequest(accessToken=test_access_token,
                                                                hostIp=test_host_ip,
                                                                appInstanceId='ed925fe22c3f4df3a1d23fa6152ab91b'))
    print(response.status)


if __name__ == '__main__':
    with grpc.insecure_channel('localhost:8234') as channel:
        stub = lcmservice_pb2_grpc.AppLCMStub(channel)
        # test_upload_config(stub)
        # test_remove_config(stub)
        test_instantiate(stub)
        # test_terminate(stub)
